package com.sun.gis.tools.wmts;


import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.MapContent;
import org.geotools.ows.wmts.WebMapTileServer;
import org.geotools.ows.wmts.map.WMTSMapLayer;
import org.geotools.ows.wmts.model.WMTSCapabilities;
import org.geotools.ows.wmts.model.WMTSLayer;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.JMapFrame;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 使用MapContent测试加载南京发布的wmts服务
 *
 * @author sunbt
 * @date 2023/8/27 20:13
 */
public class WMTSLoaderForNanjing {

    // TODO: 2023/10/2  南京wmts测试服务（不是标准xml）（使用token）
    public static void test() {
        try {
            String originalUrlString = "http://mapservices.njghzy.com.cn:84/njmap/NJDOM_DT/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetCapabilities&njtoken=7117bafd5ba7abd828421590d1d0124a";

            // 下载XML
            HttpURLConnection connection = (HttpURLConnection) new URL(originalUrlString).openConnection();
            InputStream inputStream = connection.getInputStream();
            String xmlContent = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));

            // 修复错误的部分
            xmlContent = xmlContent.replace("<ows:ProviderSite xlink:href=\"南京市规划和自然资源局\"/>", "<ows:ProviderSite xlink:href=\"http://correct.url/\"/>");


            // 将EPSG:4490替换为EPSG:4326
            xmlContent = xmlContent.replace("EPSG::4490", "EPSG::4326");
            // 为XML中的所有URL添加token
            String token = "njtoken=7117bafd5ba7abd828421590d1d0124a";
            xmlContent = xmlContent.replaceAll("http://mapservices.njghzy.com.cn:84/njmap/NJDOM_DT/wmts", "http://mapservices.njghzy.com.cn:84/njmap/NJDOM_DT/wmts?" + token);

            // 将修复后的XML保存到临时文件
            File tempFile = new File("/Users/sungang/Documents/code/gitee/gis-server/data/temp/fixedCapabilities.xml");
            try (OutputStream out = new FileOutputStream(tempFile)) {
                out.write(xmlContent.getBytes(StandardCharsets.UTF_8));
            }

            // 使用临时文件的URL创建WebMapTileServer
            URL fixedUrl = tempFile.toURI().toURL();
            WebMapTileServer wmts = new WebMapTileServer(fixedUrl);

            WMTSCapabilities capabilities = wmts.getCapabilities();
            List<WMTSLayer> layerList = capabilities.getLayerList();
            System.out.println(layerList);

            // 查找名为 "city_line" 的图层
            WMTSLayer wmtsLayer = null;
            for (WMTSLayer layer : layerList) {
                if ("NJDOM_2019".equals(layer.getName())) {
                    wmtsLayer = layer;
                    break;
                }
            }

            // 如果找到该图层，加载它
            if (wmtsLayer != null) {
                WMTSMapLayer mapLayer = new WMTSMapLayer(wmts, wmtsLayer);

                MapContent mapContent = new MapContent();
                mapContent.addLayer(mapLayer);


                //118.78545283889815, 32.018556485783094
                // 设置中心点
                double lon = 118.78545283889815;
                double lat = 32.018556485783094;

                // 根据缩放级别设置边界
                int zoomLevel = 10;  // 指定你想要的缩放级别
                double span = 180.0 / Math.pow(2, zoomLevel);  // 这个计算方法是一个简单的估算，可能需要调整以获得所需的精确缩放
                ReferencedEnvelope envelope = new ReferencedEnvelope(
                        lon - span, lon + span, lat - span, lat + span, DefaultGeographicCRS.WGS84);
                mapContent.getViewport().setBounds(envelope);

                // 使用 JMapFrame 显示地图
                JMapFrame.showMap(mapContent);
            } else {
                System.out.println("图层 city_line 未找到.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        test();
    }


}